package cn.openea.perpartner.rule.web.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.rule.factory.UserContext;
import cn.openea.perpartner.rule.web.entity.SysRule;
import cn.openea.perpartner.rule.web.service.ISysRuleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * (SysRuleList)表控制层
 *
 * @author Weird077
 * @since 2022-09-26 17:00:13
 */
@Api(tags = "规则管理")
@RestController
@RequestMapping("/rule")
public class RuleController extends BaseController {

    private String codeTemplate = "package {classPath};\n" +
            "\n" +
            "import openea.perpartner.rule.util.Rdb;\n" +
            "import openea.perpartner.rule.web.service.BaseService;\n" +
            "\n" +
            "import java.util.HashMap;\n" +
            "import java.util.List;\n" +
            "import java.util.Map;\n" +
            "\n" +
            "/**\n" +
            " * @author {author}\n" +
            " * @description {TODO}\n" +
            " * @date {date}\n" +
            " */\n" +
            "public class {ClassName} extends BaseService {\n" +
            "    @Override\n" +
            "    public String run(HashMap<String, Object> params) {\n" +
            "        \n" +
            "        return \"\";\n" +
            "    }\n" +
            "}\n";

    /**
     * 服务对象
     */
    @Resource
    private ISysRuleService ruleService;
    @ApiOperation("规则列表")
    @PostMapping("/list")
    public TableDataInfo selectList(String searchStr) {
        startPage();
        List<SysRule> list = ruleService.selectList(searchStr);
        return getDataTable(list);
    }
    @ApiOperation("规则详情")
    @GetMapping("{ruleId}")
    public AjaxResult selectOne(@PathVariable Serializable ruleId) {
        return success(ruleService.getById(ruleId));
    }

    @ApiOperation("保存规则")
    @PostMapping("/save")
    public AjaxResult saveOrUpdate(@RequestBody SysRule sysRule) {
        if (Objects.isNull(sysRule.getRuleId())) {
            String classPath = "openea.perpartner.rule.web.service.impl";
            if(StrUtil.isNotBlank(sysRule.getClassPath())){
                classPath = sysRule.getClassPath();
            }
            codeTemplate = codeTemplate.replace("{classPath}", classPath)
                    .replace("{author}", Objects.requireNonNull(StrUtil.isNotBlank(UserContext.getUserName()) ? UserContext.getUserName() : UserContext.getUserId()))
                    .replace("{TODO}", sysRule.getRuleName())
                    .replace("{date}", DateUtil.now())
                    .replace("{ClassName}", sysRule.getRuleNum());
            sysRule.setRuleCode(codeTemplate);
            sysRule.setCreateUser(UserContext.getUserId());
            sysRule.setCreateUserName(UserContext.getUserName());
        }
        return ruleService.saveOrUpdate(sysRule) ? success() : error();
    }
    @ApiOperation("删除规则")
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestBody List<Long> idList) {
        return success(ruleService.removeByIds(idList));
    }
    @ApiOperation("保存编译")
    @PostMapping("/saveAndCompile")
    public AjaxResult saveAndCompile(@RequestBody SysRule sysRule) {
        return  ruleService.saveAndCompile(sysRule)?success("编译成功！"):error("编译失败！");
    }
    @ApiOperation("运行预览")
    @GetMapping("/preview/{ruleNum}")
    public String preview(@PathVariable String ruleNum) throws ClassNotFoundException {

        return ruleService.preview(ruleNum);
    }
    @ApiOperation("校验重复")
    @GetMapping("/check/{ruleNum}")
    public AjaxResult checkRuleUnique(@PathVariable String ruleNum)   {
        return ruleService.checkRuleUnique(ruleNum)?error("规则编号已存在，请重新定义"):success("规则编号唯一，可定义");
    }


}

